let ros = null
let commandPub = null
let connected = false
let currentAlt = 0

export default {
  connect(callback) {
    ros = new ROSLIB.Ros({ url: 'ws://localhost:9090' })
    ros.on('connection', () => {
      console.log('Connected to rosbridge');
      connected = true;
    })

    ros.on('error', (err) => console.error('Error connecting to rosbridge:', err))
    ros.on('close', () => console.log('Connection to rosbridge closed'))

    const listener = new ROSLIB.Topic({
      ros: ros,
      name: '/fmu/out/vehicle_global_position',
      messageType: 'px4_msgs/VehicleGlobalPosition',
      throttle_rate: 100
    })

    listener.subscribe((message) => {
      const pos = {
        lat: message.lat,  // 示例转换，实际需处理为经纬度
        lon: message.lon
      }
      currentAlt = message.alt  // NED转ENU高度
      // console.log(currentAlt)
      // console.log(message)
      // 高度订阅
      // new ROSLIB.Topic({
      //   ros: this.ros,
      //   name: '/fmu/out/vehicle_local_position',
      //   messageType: 'px4_msgs/msg/VehicleLocalPosition',
      //   throttle_rate: 100
      // }).subscribe(msg => {
      //   this.currentAlt = -msg.z  // NED转ENU高度
      // })

      const uav_id = message.child_frame_id || 'uav1'
      callback(uav_id, pos)
    })
  },
  getROS() {
    return ros
  },
  getConnected() {
    return connected
  },
  getCurrentAlt() {
    return currentAlt
  },
  // 参数名哈希计算（PX4专用）
  hashParamName(name) {
    let hash = 0
    for (let i = 0; i < name.length; i++) {
      hash = ((hash << 5) - hash) + name.charCodeAt(i)
      hash |= 0
    }
    return hash
  }
}